package com.sunfeng.springcloud;

import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;

/**
 *
 *
 * 1.调用失败会触发降级，而降级会调用fallback方法
 * 2.但无论如何降级的流程一定会先调用正常方法再调用fallback方法
 * 3假如单位时间内调用失败次数过多，也就是降级次数过多，则触发熔断
 * 4熔断以后就会跳过正常方法直接调用fallback方法
 * 5所谓“熔断后服务不可用”就是因为跳过了正常方法直接执行fallback
 * @author sunfeng
 * @date 2021/04/01 16:05
 **/
@SpringBootApplication
@EnableEurekaClient
@EnableCircuitBreaker //对Hystrix熔断机制的支持   服务端服务降级
@SpringCloudApplication
public class PaymentHystrixMain8001 {
    public static void main(String[] args) {
        SpringApplication.run(PaymentHystrixMain8001.class, args);
    }
    /**
     *此配置是为了服务监控而配置，与服务容错本身无关，springCloud升级后的坑
     *ServletRegistrationBean因为springboot的默认路径不是"/hystrix.stream"，
     *只要在自己的项目里配置上下面的servlet就可以了
     *否则，Unable to connect to Command Metric Stream 404
     */
    @Bean
    public ServletRegistrationBean getServlet() {
        HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);
        registrationBean.setLoadOnStartup(1);
        registrationBean.addUrlMappings("/hystrix.stream");
        registrationBean.setName("HystrixMetricsStreamServlet");
        return registrationBean;
    }

}
